/**
 * 判断点是否在多边形内
 * @param {Object} point - 用户位置 {latitude, longitude}
 * @param {Array} polygon - 多边形顶点数组 [{latitude, longitude}, ...]
 * @returns {Boolean} 点是否在多边形内
 */
function isPointInPolygon(point, polygon) {
  let isInside = false;
  var x = point.longitude;
  var y = point.latitude;
  
  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    var xi = polygon[i].longitude;
    var yi = polygon[i].latitude;
    var xj = polygon[j].longitude;
    var yj = polygon[j].latitude;
    
    var intersect = ((yi > y) !== (yj > y)) && 
      (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
      
    if (intersect) isInside = !isInside;
  }
  
  return isInside;
}

/**
 * 获取用户当前位置并判断是否在指定多边形区域内
 * @param {Array} polygonPoints - 多边形顶点坐标数组 [{latitude, longitude}, ...]
 * @returns {Promise} 返回一个Promise，resolve结果为布尔值
 */
function checkUserInPolygon(userPoint,polygonPoints) {
  return new Promise((resolve, reject) => {
   /*  uni.getLocation({
      type: 'wgs84',
      success: function(res) {
        const userPoint = {
          latitude: res.latitude,
          longitude: res.longitude
        };
        const result = isPointInPolygon(userPoint, polygonPoints);
        resolve(result);
      },
      fail: function(err) {
        reject(new Error('获取用户位置失败: ' + JSON.stringify(err)));
      }
    }); */
    const result = isPointInPolygon(userPoint, polygonPoints);
       resolve(result);
  });
}

export {
  isPointInPolygon,
  checkUserInPolygon
}